package com.zj.imageloader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.LruCache;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by zj on 2018/3/13.
 */

public class ImageLoader {

    private ImageCache mImageCache = new MemoryCache();

    public ImageLoader() {
    }

    // 注入缓存实现
    public void setImageCache(ImageCache imageCache) {
        if (imageCache != null)
            mImageCache = imageCache;
    }

    /**
     * 加载图像，并进行缓存
     *
     * @param url
     * @return
     */
    public Bitmap loadImage(String url) {
        Bitmap bmp = mImageCache.get(url);
        if (bmp == null) {
            bmp = downloadImage(url);
            mImageCache.put(url, bmp);
        }

        return bmp;
    }

    private Bitmap downloadImage(String imageUrl) {
        Bitmap bitmap = null;
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            bitmap = BitmapFactory.decodeStream(connection.getInputStream());
            connection.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 更新图像，如果之前url地址的图像更新了
     *
     * @param url
     * @return
     */
    public Bitmap updateImage(String url) {
        Bitmap bmp = downloadImage(url);
        mImageCache.put(url, bmp);
        return bmp;
    }
}
